package com.permission_server.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.permission_server.entity.SysUserEntity;
import com.permission_server.entity.SysUserRoleEntity;
import com.permission_server.service.SysUserRoleService;
import com.permission_server.service.SysUserService;
import com.permission_server.util.PhotoHandler;
import com.permission_server.util.RedisUtil;
import com.permission_server.util.responseUtil.ResponseEnum;
import com.permission_server.util.responseUtil.ResponseUtil;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.Jedis;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/user")
@Api(tags = "用户管理接口")
public class UserController {

    static Jedis redis = RedisUtil.getRedis();

    @Autowired
    SysUserService sysUserService;

    @Autowired
    SysUserRoleService sysUserRoleService;

    @Autowired
    PhotoHandler photoHandler;

    @GetMapping("/pullAllUser")
    public ResponseUtil pullAllUser() {
        List<SysUserEntity> list = sysUserService.list();
        list.forEach(item -> {
            item.setSalt(null);
        });
        return ResponseUtil.setE(ResponseEnum.OK).setData(list);
    }

    @Transactional
    @PostMapping("/updateUser")
    public ResponseUtil updateUser(@RequestBody SysUserEntity user) {
        if (ObjectUtil.isEmpty(user)) return ResponseUtil.setE(ResponseEnum.PARAMS_ERROR);
        SysUserEntity sysUserEntity = LoginController.getCurrentLoginUserInfo();
        if (StrUtil.isEmpty(user.getId())) {
            user.setCreateBy(sysUserEntity.getUsername());
            user.setCreateTime(new Date());
            user.setUpdateBy(sysUserEntity.getUsername());
            user.setUpdateTime(new Date());
            user.setSalt(RandomUtil.randomString(6));
        } else {
            user.setUpdateBy(sysUserEntity.getUsername());
            user.setUpdateTime(new Date());
            user.setSalt(null);
        }
        try {
            sysUserService.saveOrUpdate(user);
            ArrayList<SysUserRoleEntity> list = new ArrayList<>();
            for (String roleId : user.getRoleIds()) {
                SysUserRoleEntity sysUserRoleEntity = new SysUserRoleEntity();
                sysUserRoleEntity.setUserId(user.getId());
                sysUserRoleEntity.setRoleId(roleId);
                list.add(sysUserRoleEntity);
            }
            LambdaQueryWrapper<SysUserRoleEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(SysUserRoleEntity::getUserId, user.getId());
            sysUserRoleService.remove(lambdaQueryWrapper);
            sysUserRoleService.saveBatch(list);
            user.setSalt(null);
            return ResponseUtil.setE(ResponseEnum.OK).setData(user).setMsg("用户【" + user.getUsername() + "】更新成功");
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("用户【" + user.getUsername() + "】更新失败");
        }
    }

    @PostMapping("/delUser")
    public ResponseUtil delUser(@RequestBody String[] idList) {
        if (ObjectUtil.isEmpty(idList)) return ResponseUtil.setE(ResponseEnum.PARAMS_ERROR);
        if (sysUserService.removeByIds(Arrays.asList(idList)))
            return ResponseUtil.setE(ResponseEnum.OK).setMsg("【" + idList.length + "】位用户删除成功");
        return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("【" + idList.length + "】位用户删除失败");
    }

    @PostMapping("/uploadAvatar")
    public ResponseUtil uploadAvatar(MultipartFile file, String mainPath) {
        if (file != null) {
            if (mainPath == "") {
                mainPath = JSONObject.parseObject(redis.get(StpUtil.getLoginId().toString()), SysUserEntity.class).getId();
            }
            File save = photoHandler.savePhoto(file, mainPath, "UserAvatar");
            String absolutePath = save.getAbsolutePath();
            String aStatic = absolutePath.substring(absolutePath.indexOf("static") + "static".length());
            return ResponseUtil.setE(ResponseEnum.OK).setData(aStatic);
        }
        return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("图片上传失败");
    }

    @GetMapping("/pullAllUserRole")
    public ResponseUtil pullAllUserRole() {
        return ResponseUtil.setE(ResponseEnum.OK).setData(sysUserRoleService.list());
    }
}
